<?php

namespace Weixin;

use Weixin;

include_once('./Application/Weixin/Weixin.conf.php');
class Api {


    public $msgtype = 'text';   
    public $msg = array();


   public function __construct($appId, $appSecret) {
      $this->appId = $appId;
      $this->appSecret = $appSecret;
      $this->access_token = $this->getAccessToken($this->appId,$this->appSecret);
    }
    
    /**
     * 获取 微信 accesstoken
     */
    public function getAccessToken($app_id, $secret) {
        $url = sprintf(ACCESS_TOKEN_URL, $app_id, $secret);
        if(strlen($_SESSION['access_token'])>1 && time()-$_SESSION['token_time']>3600){
            
        }else{
            $re = $this->achieve($url);
            $_SESSION['access_token'] = $re['access_token'];
            $_SESSION['token_time'] = time();
        }
        return $_SESSION['access_token'];
    }

    /**
     * 微信  接受消息
     */
   
    public function getMsg(){
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)) {
            $this->msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $this->msgtype = strtolower($this->msg['MsgType']);
        }
    }
    /**
     * 微信  回复消息
     */
      public function makeText($text=''){
        $CreateTime = time();
        $textTpl = "<xml>
            <ToUserName><![CDATA[{$this->msg['FromUserName']}]]></ToUserName>
            <FromUserName><![CDATA[{$this->msg['ToUserName']}]]></FromUserName>
            <CreateTime>{$CreateTime}</CreateTime>
            <MsgType><![CDATA[text]]></MsgType>
            <Content><![CDATA[%s]]></Content>
            <FuncFlag>0</FuncFlag>
            </xml>";
        return sprintf($textTpl,$text);
    }
    
    /**
     * 微信群发消息
     */
    public function sendMsgAll($sendType,$data,$touser=array()){
        $massArrayData=array();  
          switch($sendType){  
              case 'text':   //文本  
                  $massArrayData=array(  
                      "touser"=>$touser,  
                      "msgtype"=>'text',  
                      "text"=>array('content'=>$data),  
                  );  
                  break;  
              case 'news':   //图文  
                  $massArrayData=array(  
                      "touser"=>$touser,  
                      "msgtype"=>'mpnews',  
                      "mpnews"=>array('media_id'=>$data),  
                  );  
                  break;       
          } 
         $url= sprintf(SENDALL,$_SESSION['access_token']);  
         $json = urldecode(json_encode($massArrayData));
         $calldata=$this->achieve($url,$json);  
         return $calldata;       
    }
    /** 
       *   获取用户列表 
       *   $next_openid 表示从第几个开始,如果为空 默认从第一个用户开始拉取 
        */  
        public function getUserList($next_openid=null){  
            $url= sprintf(OPENID,$_SESSION['access_token'],$next_openid);
            $resultData=$this->achieve($url);          
            return $resultData;  
        }
          /** 
          *上传多媒体文件 
          *type 图片（image）缩略图（thumb）  
         */  
    public function uploadMedia($type, $file){ 
        $file_arr = explode('.', $file);
        $suffix = array_pop($file_arr);
        $size = filesize(MAIN_APP_PATH.$file);
        $data=array("thumb"  => "@".MAIN_APP_PATH.$file);
        $headers=array( "Content-Length :$size",'Content-Type: image/'.$suffix,'Content-Type :multipart/form-data',
                        "Content-Disposition: attachment; filename=".basename($file));
        $url= sprintf(UPLOAD_MEDIA,$_SESSION['access_token'],$type); 
        $resultData=$this->achieve($url,$data);
        //var_dump($resultData);
        return $resultData;  
    }  
    //上传图文消息内容中的图片，并获取url  
    public function getMediaUrl($type,$file){  
        $file_arr = explode('.', $file);
        $suffix = array_pop($file_arr);
        $size = filesize(MAIN_APP_PATH.$file);
        $data=array("thumb"  => "@".MAIN_APP_PATH.$file);
        $headers=array( "Content-Length :$size",'Content-Type: image/'.$suffix,'Content-Type :multipart/form-data',
                        "Content-Disposition: attachment; filename=".basename($file));
        $url=sprintf(GET_URL,$_SESSION['access_token']);  
        $res=$this->achieve($url, $data);  
        $picUrl = $res['url'];  
        return $picUrl;  
    }  
         /** 
         * @param $data 
         * @return mixed 
         *   上传图文素材 
         */  
    public  function  newsUpload($articles){  
      foreach($articles as $k=>$v){
            $articles[$k] = urlencode($v);
        }
        $articles=array( 'articles'=>array($articles) );  
        $url=sprintf(NEWS_UPLOAD,$_SESSION['access_token']);  
        $calldata=$this->achieve($url,urldecode(json_encode($articles)));  
        return  $calldata;  
    }   


   

    
    private function achieve($url,$data,$timeout=300){
	    $curl = curl_init(); 
	    curl_setopt($curl, CURLOPT_URL, $url);
      curl_setopt ( $curl, CURLOPT_SAFE_UPLOAD, FALSE);
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
	    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
	    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
	    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
	    curl_setopt($curl, CURLOPT_POST, 1);
	    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
      curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
	    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
	    curl_setopt($curl, CURLOPT_HEADER, false);
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	    $tmpInfo = curl_exec($curl);
	    if (curl_errno($curl)) {
	       echo 'Errno'.curl_error($curl);
	    }
	    curl_close($curl);
	    return json_decode($tmpInfo,true);
    }
    
}
